package blog

import (
	"context"
	"strconv"
	"strings"

	"github.com/infraboard/mcube/v2/ioc"
	"gitlab.com/go-course-project/go17/vblog/utils"
)

const (
	AppName = "blog"
)

func GetService() Service {
	return ioc.Controller().Get(AppName).(Service)
}

type Service interface {
	// 创建博客
	CreateBlog(context.Context, *CreateBlogRequest) (*Blog, error)
	// 博客列表查询
	QueryBlog(context.Context, *QueryBlogRequest) (*BlogSet, error)
	// 博客详情查询
	DescribeBlog(context.Context, *DescribeBlogRequest) (*Blog, error)
	// 博客编辑
	UpdateBlog(context.Context, *UpdateBlogRequest) (*Blog, error)
	// 发布
	PublishBlog(context.Context, *PublishBlogRequest) (*Blog, error)
	// 删除
	DeleteBlog(context.Context, *DeleteBlogRequest) error
}

func NewDeleteBlogRequest[T int | string](id T) *DeleteBlogRequest {
	var idValue int
	switch v := any(id).(type) {
	case int:
		idValue = v
	case string:
		parsedID, _ := strconv.ParseUint(v, 10, 0)
		idValue = int(parsedID)
	}

	return &DeleteBlogRequest{
		GetRequest: utils.GetRequest{
			Id: uint(idValue),
		},
	}
}

type DeleteBlogRequest struct {
	utils.GetRequest
}

func NewPublishBlogRequest(id uint) *PublishBlogRequest {
	return &PublishBlogRequest{
		GetRequest: *utils.NewGetRequest(id),
	}
}

type PublishBlogRequest struct {
	utils.GetRequest
	StatusSpec
}

func NewUpdateBlogRequest(id uint) *UpdateBlogRequest {
	return &UpdateBlogRequest{
		GetRequest: *utils.NewGetRequest(id),
	}
}

type UpdateBlogRequest struct {
	utils.GetRequest
	CreateBlogRequest
}

func NewDescribeBlogRequest(id uint) *DescribeBlogRequest {
	return &DescribeBlogRequest{
		GetRequest: *utils.NewGetRequest(id),
	}
}

type DescribeBlogRequest struct {
	utils.GetRequest
}

func NewQueryBlogRequest() *QueryBlogRequest {
	return &QueryBlogRequest{
		PageRequest: *utils.NewPageRequest(),
		Tags:        map[string]string{},
	}
}

type QueryBlogRequest struct {
	// 分页参数
	utils.PageRequest
	// 文章标题模糊匹配,  Golang
	Keywords string `json:"keywords" form:"keywords"`
	// 状态过滤参数, 作者：nil, 访客: STAGE_PUBLISHED
	Stage *STAGE `json:"stage" form:"stage"`
	// 查询某个用户具体的文章: 给作者用的
	CreateBy string `json:"create_by" form:"create_by"`
	// 分类
	Category string `json:"category" form:"category"`
	// 查询Tag相关的文章
	// 	SELECT *
	// FROM my_table
	// WHERE data->>'$.name' = '某个名字';
	Tags map[string]string `json:"tag" form:"-"`
}

// tags=key=value,key=value
// key=value,key=value
// key=value
func (r *QueryBlogRequest) SetTag(tag string) {
	kvItem := strings.Split(tag, ",")
	for i := range kvItem {
		kvString := kvItem[i]
		kv := strings.Split(kvString, "=")
		if len(kv) > 1 {
			r.Tags[kv[0]] = strings.Join(kv[1:], "=")
		}
	}
}
